import { useLocationStore, useMemberStore } from '@/stores'
import type { locationType } from '@/types/component'
import { QQMapWX } from '@/static/qqmap-wx-jssdk'
import { getBalanceApi, getHasPayPasswordApi, getPayPasswordFreeApi } from '@/services/wallet'

/**
 * * 文字提示
 * @param 'success' | 'error'
 * @param 默认为 'none'
 */
export const Toast = (title: string, icon: 'none' | 'success' | 'error' = 'none') => {
  if (title) {
    uni.showToast({ title, icon })
  }
}
/**
 * * 页面跳转
 * @param url 跳转路径
 * @param type 跳转方式
 */
export const PageSkip = (
  url?: string | 'navigateBack',
  type: 'navigateTo' | 'redirectTo' | 'reLaunch' | 'switchTab' = 'navigateTo',
) => {
  console.log('PageSkip', url)
  if (url === 'navigateBack') {
    return uni.navigateBack()
  }
  switch (type) {
    case 'navigateTo':
    case 'redirectTo':
    case 'reLaunch':
    case 'switchTab': {
      if (url) {
        // 只有当 url 存在时才使用
        const options = { url }
        if (type === 'navigateTo') {
          uni.navigateTo(options)
        } else if (type === 'redirectTo') {
          uni.redirectTo(options)
        } else if (type === 'reLaunch') {
          uni.reLaunch(options)
        } else if (type === 'switchTab') {
          uni.switchTab(options)
        }
      }
      break
    }
  }
}
/**
 * 确认弹窗提示
 * @param content 提示的内容 必填
 * @param title 提示的标题 选填
 */
export const MyShowModal = (content: string, title = '') => {
  return new Promise<UniApp.ShowModalRes>((resolve, reject) => {
    uni.showModal({
      title,
      content,
      confirmColor: '#ffc65d',
      success: (success: UniApp.ShowModalRes) => {
        resolve(success)
      },
      fail: (err) => {
        reject(err)
      },
    })
  })
}

/**
 * * 时间转换并且 补零
 * @param time
 * @param type !s 除去秒数， YMD 年月日，YM 年月， MD 月日， 不传就代表过滤到秒
 */
export const SwitchingTime = (time: any, type?: string) => {
  // if (typeof time !== 'number') return ''

  const date = new Date(time)

  if (isNaN(date.getTime())) return ''

  const Y = date.getFullYear()
  const M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  const D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  const h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
  const m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  const s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  switch (type) {
    case 'YMD':
      return Y + '-' + M + '-' + D + ' '
    case '年月日':
      return Y + '年' + M + '月' + D + '日'
    case 'MD':
      return M + '-' + D + ' '
    case '月日':
      return M + '月' + D + '日'
    case 'YM':
      return Y + '-' + M
    case '年月':
      return Y + '年' + M + '月'
    case 'HMS':
      return h + ':' + m + ':' + s
    case 'HM':
      return h + ':' + m
    case 'MS':
      return m + ':' + s
    case '!s':
      return Y + '-' + M + '-' + D + ' ' + h + ':' + m
    default:
      return Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s
  }
}
/** 根据传入的m，自动转换回km */
export const SwitchingDistance = (distance: string) => {
  const dist = distance.replace('m', '')
  if (dist === 'undefined' || dist === 'null' || dist === '') return ''
  if (Number(dist) > 1000) {
    return (Number(dist) / 1000).toFixed(2) + 'km'
  } else {
    return distance
  }
}
/**最小值为0.01 */
export const MinPrice = (price: number) => {
  return price <= 0.01 ? 0.0 : price
}

/**判断用户是否开启定位权限 */
export const IsUserLocationPermission = (func?: Function) => {
  const locationStore = useLocationStore()
  uni.getLocation({
    type: 'gcj02',
    success: (success: UniApp.GetLocationSuccess) => {
      let location = <locationType>{
        latitude: success.latitude + '',
        longitude: success.longitude + '',
      }
      locationStore.setLocation(location)
      console.log('判断用户是否开启定位权限', location)
      func && func()
    },
    fail: (error) => {
      console.log({ error })
      if (error.errCode === 2) {
        MyShowModal(
          '请在系统设置中打开位置授权后重新进入小程序，以便我们为您提供更好的服务',
          '您未开启地理位置授权',
        )
      } else {
        MyShowModal(
          '请在系统设置中打开位置授权后重新进入小程序，以便我们为您提供更好的服务',
          '您未开启地理位置授权',
        ).then((res) => {
          if (res.confirm) {
            wx.openSetting()
          }
        })
      }
    },
  })
}
/**获取城市名称 */
export const getCityName = () => {
  console.log('获取城市名称', QQMapWX)
  const locationStore = useLocationStore()
  return new Promise((resolve, reject) => {
    uni.getLocation({
      type: 'gcj02',
      success: (success: UniApp.GetLocationSuccess) => {
        let location = <locationType>{
          latitude: success.latitude + '',
          longitude: success.longitude + '',
        }
        try {
          const qqMap = new QQMapWX({ key: '4MEBZ-2NCW4-OS7UA-KT3GT-3SSNQ-OYFOX' })  // 6JIBZ-TC2L5-GLSI5-ITHCD-FHVQF-GBB2D
          console.log('获取城市名称::::::qqMap', qqMap.reverseGeocoder)
          qqMap?.reverseGeocoder({
            options: location,
            success: (res: any) => {
              if (res.result && res.result.address_component.city) {
                location = { ...location, cityName: res.result.address_component.city }
                console.log({ location })
                locationStore.setLocation(location)
                resolve(location)
              }
            },
            fail: () => {
              Toast('获取城市信息失败')
              reject()
            },
          })
        } catch (error) {
          location = { ...location, cityName: '杭州市' }
          locationStore.setLocation(location)
          Toast('获取城市信息失败, 给予默认城市')
          reject(error)
        }
      },
      fail: (error) => {
        if (error.errCode === 2) {
          MyShowModal(
            '请在系统设置中打开位置授权后重新进入小程序，以便我们为您提供更好的服务',
            '您未开启地理位置授权',
          )
        } else {
          MyShowModal(
            '请在系统设置中打开位置授权后重新进入小程序，以便我们为您提供更好的服务',
            '您未开启地理位置授权',
          ).then((res) => {
            if (res.confirm) {
              wx.openSetting()
            }
          })
        }
        Toast('获取定位信息失败')
        reject(error)
      },
    })
  })
}

/**用正则拿到传参 */
export const extractQueryParams = (url: any) => {
  // 使用正则表达式匹配查询参数
  const match = url.match(/\?(.*)/)
  if (!match) return {}

  // 解析查询字符串
  const queryParams = match[1]
  const params = queryParams.split('&').reduce((acc: any, param: any) => {
    const [key, value] = param.split('=')
    acc[key] = decodeURIComponent(value)
    return acc
  }, {})

  return params
}

import useQuery from '@/hooks/useQuery'
/**获取外部跳转小程序的参数 */
export const getExternalSkipMiniApp = (ev?: any) => {
  let query: any = extractQueryParams(decodeURIComponent(ev?.q))
  if (!query || Object.keys(query).length === 0) {
    console.log('进入新用户处理', query)
    query = extractQueryParams(decodeURIComponent(decodeURIComponent(ev?.q)))
  }

  useQuery().setQueryParams(query)
}

// 获取用户钱包余额
export const getBalance = async () => {
  const memberStore = useMemberStore()
  const res = await getBalanceApi()
  if (res.code === 200) {
    memberStore.setBalanceInfo(res.data)
  }
}

// 是否开启免密支付
export async function getPayPasswordFree() {
  const memberStore = useMemberStore()
  const res = await getPayPasswordFreeApi()
  if (res.code === 200) {
    memberStore.setHasPayPasswordFree(res?.data)
  }
}

// 获取用户是否存在支付密码
export const getHasPayPassword = async () => {
  const memberStore = useMemberStore()
  const res = await getHasPayPasswordApi()
  if (res.code === 200) {
    memberStore.setHasPayPassword(res.data)
  }
}
